﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Threading;
using System.Data;

//自定义命名空间
using DreamCube.Foundation.Basic.Utility;
using DreamCube.Apps.Common.WinForm.Controls;
using DreamCube.Apps.Common.WinForm.Controls.Progress;

namespace AutoCompile.UI
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 最后选中的项的文本
        /// </summary>
        private String lastConfigSelectText = "";

        private String managerItemText = "管理...";
        private String addItemText = "新建...";

        /// <summary>
        /// 标志是否已经保存了当前项
        /// </summary>
        private Boolean savedCurrentItem = false;

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择devenv.exe目录按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "exe文件(*.exe)|*.exe";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.InitialDirectory = @"";
            openFileDialog1.Multiselect = false;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }

        /// <summary>
        /// 添加项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex < 0)
            {
                MessageBox.Show("请选择指定的配置项，再添加项目文件", "提醒");
                return;
            }
            AddProject addForm = new AddProject();
            if (addForm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                for (Int32 i = 0; i < addForm.SelectProjects.Count; i++)
                {
                    Object[] values = new Object[] 
                    { 
                        addForm.SelectProjects[i][0],
                        addForm.SelectProjects[i][1],
                        addForm.FrameworkVersion,
                        addForm.OutputPath,
                        addForm.SelectProjects[i][2],
                        addForm.SelectProjects[i][3]
                    };
                    dataGridView1.Rows.Add(values);

                    //修改配置的话，则标志当前配置没有保存
                    savedCurrentItem = false;
                }
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadConfigs()
        {
            comboBox1.Items.Clear();
            List<String> configNames = ConfigsHelper.GetAllConfigNames();
            String defaultName =ConfigsHelper.GetDefaultConfigName();
            for (Int32 i = 0; i < configNames.Count; i++)
            {
               Int32 index = comboBox1.Items.Add(configNames[i]);
                if(configNames[i] == defaultName)
                    comboBox1.SelectedIndex = index;
            }
            comboBox1.Items.Add(managerItemText);
            comboBox1.Items.Add(addItemText);
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            LoadConfigs();
            lastConfigSelectText = comboBox1.Text;
        }

        /// <summary>
        /// 选中新建按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lastConfigSelectText == comboBox1.Text) return;
            if (!savedCurrentItem && lastConfigSelectText!="")
            {
                if (MessageBox.Show("当前配置还没有保存，确定放弃当前保存当前配置信息切换到别的配置吗？", "提醒", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                {
                    comboBox1.Text  = lastConfigSelectText;
                    return;
                }
            }
            if (comboBox1.Text == addItemText)
            {
                //comboBox1.Text = lastConfigSelectText;
                String items = String.Empty;
                for (Int32 i = 0; i < comboBox1.Items.Count - 2; i++)
                {
                    if (i == 0) items += comboBox1.Items[i];
                    else items += ";" + comboBox1.Items[i];
                }
                AddConfig configForm = new AddConfig(items);
                if (configForm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    comboBox1.Items.Insert(comboBox1.Items.Count - 2, configForm.ConfigName);
                    comboBox1.SelectedItem = configForm.ConfigName;
                    dataGridView1.Rows.Clear();
                    //savedCurrentItem = false;
                    //保存配置项名字
                    ConfigsHelper.ConfigNode(configForm.ConfigName, null);
                }
                else 
                {
                    if (comboBox1.Items.Count > 0)
                    {
                        for (Int32 i = 0; i < comboBox1.Items.Count; i++)
                        {
                            if (comboBox1.Items[i].ToString() == lastConfigSelectText)
                                comboBox1.SelectedIndex = i;
                        }
                    }
                }
            }
            else if (comboBox1.Text == managerItemText)
            {
                EditConfig editConfig = new EditConfig();
                if (editConfig.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    LoadConfigs();
                if (comboBox1.Items.Count > 0)
                {
                    for (Int32 i = 0; i < comboBox1.Items.Count; i++)
                    {
                        if (comboBox1.Items[i].ToString() == lastConfigSelectText)
                            comboBox1.SelectedIndex = i;
                    }
                }
            }
            else
            {
                dataGridView1.Rows.Clear();
                List<ProjectElement> projects = ConfigsHelper.GetConfigProjects(comboBox1.Text);
                if (projects != null && projects.Count > 0)
                {
                    for (Int32 i = 0; i < projects.Count; i++)
                    {
                        Object[] values = new Object[] 
                                            { 
                                                projects[i].ProjectName,
                                                projects[i].ProjectPath,
                                                projects[i].FrameworkVersion,
                                                projects[i].OutputPath,
                                                projects[i].Config ,
                                                projects[i].Platform
                                            };
                        dataGridView1.Rows.Add(values);
                    }
                }
                savedCurrentItem = true;
                lastConfigSelectText = comboBox1.Text ;
            }
        }

        /// <summary>
        /// 保存按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            String configName = comboBox1.Text;
            List<ProjectElement> projects = new List<ProjectElement>();
            for (Int32 i = 0; i < dataGridView1.Rows.Count; i++)
            {
                ProjectElement pj = new ProjectElement()
                {
                    FrameworkVersion = dataGridView1.Rows[i].Cells[2].Value.ToString(),
                    OutputPath = dataGridView1.Rows[i].Cells[3].Value.ToString(),
                    ProjectName = dataGridView1.Rows[i].Cells[0].Value.ToString(),
                    ProjectPath = dataGridView1.Rows[i].Cells[1].Value.ToString(),
                    Config = dataGridView1.Rows[i].Cells[4].Value.ToString(),
                    Platform = dataGridView1.Rows[i].Cells[5].Value.ToString(),
                };
                projects.Add(pj);
            }
            ConfigsHelper.ConfigNode(configName, projects);

            //标志当前的配置已经保存
            savedCurrentItem = true;
            MessageBox.Show("保存成功", "提醒");
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            savedCurrentItem = false;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("确定要删除选中的项目", "确认提醒", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                    return;
            }
            for (Int32 j = dataGridView1.Rows.Count - 1; j >= 0; j--)
            {
                if (dataGridView1.Rows[j].Selected)
                    dataGridView1.Rows.RemoveAt(j);
            }
        }

        /// <summary>
        /// 窗体关闭前触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            String msg = "确定要退出系统吗？";
            if (lastConfigSelectText != comboBox1.Text && !savedCurrentItem)
                msg = "您修改了当前配置信息还没保存，确定放弃保存并退出程序吗？";
            if (MessageBox.Show(msg, "退出系统提醒", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            //this.Close();
        }

        private Boolean hasDone = false;

        /// <summary>
        /// 生成按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //禁用按钮
            button2.Enabled = false;
            Action a = new Action(() =>
            {
                Int32 totalRow = 0;
                ControlHelper.ControlInvoke(this, new Action(() => {
                    totalRow = dataGridView1.Rows.Count;
                }));
                for (Int32 i = 0; i < totalRow; i++)
                {
                    ProjectElement projectElement = null;
                    ControlHelper.ControlInvoke(this, new Action(() => {
                        projectElement = new ProjectElement()
                        {
                            Config = dataGridView1.Rows[i].Cells[4].Value.ToString(),
                            FrameworkVersion = dataGridView1.Rows[i].Cells[2].Value.ToString(),
                            OutputPath  = dataGridView1.Rows[i].Cells[3].Value.ToString(),
                            Platform = dataGridView1.Rows[i].Cells[5].Value.ToString(),
                            ProjectName = dataGridView1.Rows[i].Cells[0].Value.ToString(),
                            ProjectPath = dataGridView1.Rows[i].Cells[1].Value.ToString()
                        };
                    }));

                    if (radioButton1.Checked)
                    {
                        //先更新源码
                        SVNHelper.UpdatePath(projectElement.ProjectPath);
                    }
                    //再进行编译
                    //Compile
                    CompileHelper.Compile(textBox1.Text, projectElement);
                }
            });
            a.BeginInvoke(new AsyncCallback((o) =>
            {
                hasDone = true;
            }), null);

            Thread thread = new Thread(new ThreadStart(() =>
            {
                while (!hasDone)
                {
                    Thread.Sleep(800); //睡眠时间
                    Action updateProgressBarAction = new Action(() =>
                    {
                        if (progressBar1.Value == progressBar1.Maximum) //重置滚动条
                            progressBar1.Value = 0;
                        progressBar1.Value++;
                    });
                    if (progressBar1.InvokeRequired)
                        progressBar1.Invoke(updateProgressBarAction);
                    else
                    {
                        updateProgressBarAction.Invoke();
                    }
                }
            }));
            thread.Start();
        }

        private void upOrdownOrDelete(string type)
        {
            if (this.dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请选择要需要操作行");
            }
            else if (type == "del")//删
            {
                if (MessageBox.Show("确定要删除吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
                }
            }
            else if (type == "up")//上
            {
                if (this.dataGridView1.CurrentRow.Index <= 0)
                {
                    MessageBox.Show("此行已在顶端，不能再上移！");
                }
                else
                {
                    int nowIndex = this.dataGridView1.CurrentRow.Index;
                    MyDataGridView.MoveRow(dataGridView1, nowIndex, nowIndex - 1);
                }
            }
            else if (type == "down")//下
            {
                if (this.dataGridView1.CurrentRow.Index >= this.dataGridView1.Rows.Count - 1)
                {
                    MessageBox.Show("此工序已在底端，不能再下移！");
                }
                else
                {
                    int nowIndex = this.dataGridView1.CurrentRow.Index;
                    MyDataGridView.MoveRow(dataGridView1, nowIndex, nowIndex + 1);
                }
            }
        }

        /// <summary>
        /// 下移按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            upOrdownOrDelete("down");
        }

        /// <summary>
        /// 上移按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(Object sender, EventArgs e)
        {
            upOrdownOrDelete("up");
        }

        /// <summary>
        /// 选择常用输出目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(Object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox2.Text = folderBrowserDialog1.SelectedPath ;
            }
        }

        /// <summary>
        /// 保存配置信息按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(Object sender, EventArgs e)
        {
            ConfigsHelper.SaveOutputPath(textBox2.Text);
            ConfigsHelper.SaveDevenvPath(textBox1.Text);
            MessageBox.Show("保存成功", "提醒");
        }
        
        /// <summary>
        /// 鼠标单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_MouseClick(Object sender, MouseEventArgs e)
        {

        }

        /// <summary>
        /// 选中不同的tab页面的时候触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                textBox1.Text = ConfigsHelper.GetDevenvPath();
                textBox2.Text = ConfigsHelper.GetOutputPath();
            }
        }
    }
}
